<template>
  <div class="app-container">
    <div class="Header">
      <edit-form ref="filterContainer" v-show="showSearch" :editFormMap="filterMap" :editFormData="queryParams">
        <template slot="buttonGroup">
          <el-col :span="4">
            <el-form-item class="buttonGroup">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </template>
      </edit-form>
      <handle-button-group
        :showSearch.sync="showSearch"
        :single="single"
        :multiple="multiple"
        :authModule="{ module: 'question', name: 'ab' }"
        @handleAdd="handleAdd"
        @handleUpdate="handleUpdate"
        @handleDelete="handleDelete"
        @handleExport="handleExport"
        @getList="getList"
      />
    </div>
    <table-list
      ref="tableListContainer"
      :tableListMap="tableMap"
      :request="{
        apiKey: 'AbQuestList',
        params: queryParams,
        method: 'get',
      }"
      @selection-change="handleSelectionChange"
      @changeTableListAction="
        (TableList) => {
          userList = TableList;
        }
      "
    >
      <template slot="hasSelect">
        <el-table-column type="selection" width="55" :align="'center'" />
      </template>
      <template slot="hasHandle">
        <el-table-column label="操作" :align="'center'">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['question:ab:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['question:ab:remove']">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </table-list>
    <!-- 添加或修改共同题对话框 -->
    <el-dialog :title="title" :visible.sync="open" top="0vh" width="1200px" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">
      <div>
        <h2>男生题</h2>
        <basicQuest
          ref="manQuestionBasicQuest"
          :basicForm="manQuestion"
          :basicFormData.sync="params.manQuestion"
          :questionDirect="manQuestionDirect"
          :basicQuestionDirect.sync="params.manQuestionDirect"
        ></basicQuest>
        <answerOption ref="manQuestionAnswerOption" :optionList="manOptionList" :answerOptionList.sync="params.manOptionList" type="ab" />
      </div>
      <div style="border-top: 1px solid #c0c4cc">
        <h2>女生题</h2>
        <basicQuest
          ref="womanQuestionBasicQuest"
          :basicForm="womanQuestion"
          :basicFormData.sync="params.womanQuestion"
          :questionDirect="womanQuestionDirect"
          :basicQuestionDirect.sync="params.womanQuestionDirect"
        ></basicQuest>
        <answerOption ref="womanQuestionAnswerOption" :optionList="womanOptionList" :answerOptionList.sync="params.womanOptionList" type="ab" />
      </div>
      <!-- 和谐项 -->
      <disharmony ref="disharmony" :basicHarmonyItemList="harmonyItemList" :harmonyItemList.sync="params.harmonyItemList" type="ab" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import basicQuest from '../components/basicQuest';
import answerOption from '../components/answerOption';
import disharmony from '../components/disharmony';
import { addAb, updateAb, delAb, exportAb, getAb } from '@/api/question/ab';
import { getDataSource } from '@/static/js/dataSource';
import cloneDeep from 'lodash/cloneDeep';
export default {
  name: 'Ab',
  components: {
    basicQuest,
    answerOption,
    disharmony,
  },
  computed: {
    filterMap() {
      return getDataSource('editForm', 'questFilterMap');
    },
    tableMap() {
      return getDataSource('tableColumn', 'questTableMap');
    },
  },
  watch: {
    'params.manOptionList': {
      handler(val) {
        if (!val || !val.length) return;
        const options =
          val
            .filter((item) => item.optionTitle)
            .map((item) => {
              return {
                value: item.optionTitle,
                label: item.optionTitle,
              };
            }) || [];
        this.$nextTick(() => {
          const disharmony = this.$refs.disharmony;
          disharmony.setOptionList(options, 'man');
        });
      },
      deep: true,
      immediate: true,
    },
    'params.womanOptionList': {
      handler(val) {
        if (!val || !val.length) return;
        const options =
          val
            .filter((item) => item.optionTitle)
            .map((item) => {
              return {
                value: item.optionTitle,
                label: item.optionTitle,
              };
            }) || [];
        this.$nextTick(() => {
          const disharmony = this.$refs.disharmony;
          disharmony.setOptionList(options, 'woman');
        });
      },
      deep: true,
      immediate: true,
    },
    manOptionList: {
      handler(val) {
        if (!val || !val.length) return;
        const options =
          val
            .filter((item) => item.optionTitle)
            .map((item) => {
              return {
                value: item.optionTitle,
                label: item.optionTitle,
              };
            }) || [];
        this.$nextTick(() => {
          const disharmony = this.$refs.disharmony;
          disharmony.setOptionList(options, 'man');
        });
      },
      deep: true,
      immediate: true,
    },
    womanOptionList: {
      handler(val) {
        if (!val || !val.length) return;
        const options =
          val
            .filter((item) => item.optionTitle)
            .map((item) => {
              return {
                value: item.optionTitle,
                label: item.optionTitle,
              };
            }) || [];
        this.$nextTick(() => {
          const disharmony = this.$refs.disharmony;
          disharmony.setOptionList(options, 'woman');
        });
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      optionListMap: {},
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 表格数据
      userList: [],
      // 下拉数据对象
      tableOptionMap: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {},
      // 表单参数
      manQuestion: { specifiedRange: 0, matchSwitch: 0 },
      womanQuestion: { specifiedRange: 0, matchSwitch: 0 },
      // 定向答题
      manQuestionDirect: {},
      womanQuestionDirect: {},
      // 答题选项
      manOptionList: [],
      womanOptionList: [],
      // 和谐项
      harmonyItemList: [],
      params: {
        manQuestion: {},
        womanQuestion: {},
        manQuestionDirect: {},
        womanQuestionDirect: {},
        manOptionList: [],
        womanOptionList: [],
        harmonyItemList: [],
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.$nextTick(() => {
        this.$refs.tableListContainer.init();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.manQuestion = this.$options.data().manQuestion;
      this.womanQuestion = this.$options.data().womanQuestion;
      this.manOptionList = this.$options.data().manOptionList;
      this.womanOptionList = this.$options.data().womanOptionList;
      this.manQuestionDirect = this.$options.data().manQuestionDirect;
      this.womanQuestionDirect = this.$options.data().womanQuestionDirect;
      this.harmonyItemList = this.$options.data().harmonyItemList;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      const tableListContainer = this.$refs.tableListContainer;
      tableListContainer.pagination = tableListContainer.$options.data().pagination;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const filterContainer = this.$refs.filterContainer;
      filterContainer.resetForm('editFormData');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = '添加共同题';
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate({ id }) {
      getAb(id).then((res) => {
        this.title = '修改共同题';
        this.open = true;
        this.harmonyItemList = res.data.harmonyItemList;
        this.params.harmonyItemList = res.data.harmonyItemList;
        ['manQuestion', 'womanQuestion'].map((dataKey) => {
          const data = res.data[dataKey];
          this[dataKey] = data;
          this.params[dataKey] = data;
          Object.keys(data).map((key) => {
            const keyArr = ['themeIds'];
            const fieldArr = ['themeId'];
            if (['questionDirectResp', 'optionList'].includes(key)) {
              const dataMap = {
                questionDirectResp: dataKey + 'Direct',
                optionList: dataKey.replace('Question', '') + 'OptionList',
              };
              this[dataMap[key]] = data[key];
              this.params[dataMap[key]] = data[key];
            } else if (data[key] && keyArr.includes(key)) {
              const index = keyArr.findIndex((item) => item === key);
              const valueArr = data[key].split(',').map((item) => parseInt(item));
              this.$set(this[dataKey], fieldArr[index], valueArr);
              this.$set(this.params[dataKey], fieldArr[index], valueArr);
              this.$set(this[dataKey], key, data[key]);
              this.$set(this.params[dataKey], key, data[key]);
            } else {
              this.$set(this[dataKey], key, data[key]);
              this.$set(this.params[dataKey], key, data[key]);
            }
          });
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? row.id : this.ids.join(',');
      this.$modal
        .confirm('是否确认删除Id编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAb(ids);
        })
        .then(() => {
          this.getList();
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const tableListContainer = this.$refs.tableListContainer;
      const pagination = tableListContainer.pagination;
      const params = {
        ...pagination,
        ...this.queryParams,
      };
      exportAb(params, '共同题数据导出');
    },
    changeAction(prop) {},
    /** 提交按钮 */
    submitForm() {
      let optionFlag = true;
      if (!this.params.manOptionList.length) return this.$message.error('男生题的答题选项不能为空');
      if (!this.params.womanOptionList.length) return this.$message.error('女生题的答题选项不能为空');
      if (!this.params.harmonyItemList.length) return this.$message.error('AB题不和谐项不能为空');
      this.params.manOptionList.some((item, index) => {
        if (!item.optionTitle) {
          optionFlag = false;
          this.$message.error(`男生题的第${index + 1}行的选项名称不能为空`);
        }
      });
      this.params.womanOptionList.some((item, index) => {
        if (!item.optionTitle) {
          optionFlag = false;
          this.$message.error(`女生题的第${index + 1}行的选项名称不能为空`);
        }
      });
      if (!optionFlag) return;
      const manBasicQuest = this.$refs.manQuestionBasicQuest;
      const womanBasicQuest = this.$refs.womanQuestionBasicQuest;
      const manBasicQuestContainer = manBasicQuest.$refs.basicQuestContainer;
      const womanBasicQuestContainer = womanBasicQuest.$refs.basicQuestContainer;
      manBasicQuestContainer.$refs.editFormData.validate((manBasicValid) => {
        if (!manBasicValid) return;
        womanBasicQuestContainer.$refs.editFormData.validate((womanBasicValid) => {
          if (!womanBasicValid) return;
          const { manQuestion, manQuestionDirect, manOptionList, womanQuestion, womanQuestionDirect, womanOptionList, harmonyItemList } = this.params;
          const params = cloneDeep({
            manQuestion: { ...manQuestion, questionDirect: manQuestionDirect, optionList: manOptionList },
            womanQuestion: { ...womanQuestion, questionDirect: womanQuestionDirect, optionList: womanOptionList },
            harmonyItemList,
          });
          if (manQuestion.id && womanQuestion.id) {
            updateAb(params).then(() => {
              this.$message.success('修改成功');
              this.reset();
              this.getList();
              this.open = false;
            });
          } else {
            addAb(params).then(() => {
              this.$message.success('新增成功');
              this.open = false;
              this.getList();
            });
          }
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped></style>
